<template>
  <div class="no-background-container">
    <el-affix :offset="72">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">{{ routeName }}</div>
        </div>
        <div class="header-query">
          <el-button type="primary" @click="showFormDialog = true">新增{{ moduleName }}</el-button>
          <qs-query-form v-model="queryForm" :fields="queryFields" :loading="listLoading" @reset="resetQuery" @search="queryData" />
        </div>
      </div>
    </el-affix>

    <div class="qs-y-table-card">
      <qs-table
        border
        :columns="tableColumns"
        :data="list"
        :loading="listLoading"
        :pagination="{
          currentPage: queryForm.page,
          pageSize: queryForm.limit,
          total,
          layout,
        }"
        show-index
        stripe
        @page-change="handleCurrentChange"
        @selection-change="setSelectRows"
        @size-change="handleSizeChange"
      >
        <template #column-meetingTitle="{ row }">
          <div style="cursor: pointer" @click="handleDetails(row)">
            <div style="font-size: 12px">{{ row.contractNo || '' }}</div>
            <div style="font-size: 14px; font-weight: 500; color: var(--el-color-primary)">{{ row.meetingTitle }}</div>
          </div>
        </template>

        <template #column-attendees="{ row }">
          <el-tag v-for="(tag, tagIndex) in row.attendees" :key="tagIndex" style="margin-right: 5px">{{ tag }}</el-tag>
        </template>

        <template #operation="{ row }">
          <el-button size="small" text @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" text type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </qs-table>
    </div>

    <qs-form-dialog
      v-model="showFormDialog"
      :fields="formFields"
      :form-data="form"
      :loading="formLoading"
      :title="isEditMode ? `编辑${moduleName}` : `新增${moduleName}`"
      @cancel="showFormDialog = false"
      @confirm="handleFormSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onActivated, onBeforeMount, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import QsFormDialog from '../../components/Dialog-new/FormDialog.vue'
import QsQueryForm from '../../components/QueryForm-new/index.vue'
import QsTable from '../../components/Table-new/index.vue'

// 模拟数据
const mockData = [
  {
    id: 1,
    meetingTitle: '项目进度会议',
    date: '2023-10-01',
    startTime: '09:00:00',
    duration: 60,
    location: '会议室A',
    attendees: ['张三', '李四', '王五'],
    description: '讨论项目进度和下一步计划',
  },
  {
    id: 2,
    meetingTitle: '客户会议',
    date: '2023-10-02',
    startTime: '10:00:00',
    duration: 90,
    location: '会议室B',
    attendees: ['赵六', '孙七', '周八'],
    description: '与客户讨论合作细节',
  },
  {
    id: 3,
    meetingTitle: '内部培训',
    date: '2023-10-03',
    startTime: '14:00:00',
    duration: 120,
    location: '会议室A',
    attendees: ['吴九', '郑十', '钱十一'],
    description: '进行内部员工培训',
  },
  {
    id: 4,
    meetingTitle: '产品发布会',
    date: '2023-10-04',
    startTime: '09:30:00',
    duration: 180,
    location: '会议室B',
    attendees: ['王十二', '李十三', '张十四'],
    description: '发布新产品',
  },
  {
    id: 5,
    meetingTitle: '团队建设活动',
    date: '2023-10-05',
    startTime: '10:30:00',
    duration: 150,
    location: '会议室A',
    attendees: ['赵十五', '孙十六', '周十七'],
    description: '组织团队建设活动',
  },
]

// 表单数据
const form = ref<any>({})
const formLoading = ref(false)

// 编辑状态
const isEditMode = ref(false)

// 编辑行数据
const handleEdit = (row: any) => {
  form.value = { ...row }
  showFormDialog.value = true
  isEditMode.value = true
}

// 删除行数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 模块名称
const moduleName = '预约'

// 路由相关
const route = useRoute()
const router = useRouter()
const routeName = computed(() => route.meta.title || '')

// 表格数据
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const layout = ref<string>('total, sizes, prev, pager, next, jumper')
const total = ref<number>(0)
const selectRows = ref<any>([])

// 查询表单
const queryForm = reactive<any>({
  page: 1,
  limit: 20,
  search: '',
  meetingTitle: '',
  location: '',
})

// 查询表单字段定义
const queryFields = ref([
  {
    label: '会议主题',
    prop: 'meetingTitle',
    component: 'input',
    placeholder: '请输入会议主题',
  },
  {
    label: '会议室',
    prop: 'location',
    component: 'select',
    options: [
      { value: '会议室A', label: '会议室A' },
      { value: '会议室B', label: '会议室B' },
    ],
    placeholder: '请选择会议室',
  },
])

// 表格列定义
const tableColumns = ref([
  {
    label: '会议主题',
    prop: 'meetingTitle',
    minWidth: 200,
  },
  {
    label: '日期',
    prop: 'date',
    minWidth: 120,
  },
  {
    label: '开始时间',
    prop: 'startTime',
    minWidth: 120,
  },
  {
    label: '时长(分钟)',
    prop: 'duration',
    minWidth: 100,
  },
  {
    label: '会议室',
    prop: 'location',
    minWidth: 120,
  },
  {
    label: '与会人员',
    prop: 'attendees',
    minWidth: 200,
  },
  {
    label: '会议描述',
    prop: 'description',
    minWidth: 200,
  },
])

// 表单字段定义
const formFields = ref([
  {
    label: '会议主题',
    prop: 'meetingTitle',
    component: 'input',
    required: true,
    placeholder: '请输入会议主题',
    colSpan: 24,
  },
  {
    label: '日期',
    prop: 'date',
    component: 'date-picker',
    required: true,
    placeholder: '请选择日期',
    colSpan: 12,
  },
  {
    label: '开始时间',
    prop: 'startTime',
    component: 'time-picker',
    required: true,
    placeholder: '请选择开始时间',
    colSpan: 12,
  },
  {
    label: '时长',
    prop: 'duration',
    component: 'input-number',
    required: true,
    placeholder: '请输入时长（分钟）',
    colSpan: 12,
  },
  {
    label: '会议室',
    prop: 'location',
    component: 'select',
    options: [
      { value: '会议室A', label: '会议室A' },
      { value: '会议室B', label: '会议室B' },
    ],
    required: true,
    placeholder: '请选择会议室或地点',
    colSpan: 12,
  },
  {
    label: '与会人员',
    prop: 'attendees',
    component: 'select',
    options: [
      { value: '张三', label: '张三' },
      { value: '李四', label: '李四' },
      { value: '王五', label: '王五' },
      { value: '赵六', label: '赵六' },
    ],
    multiple: true,
    required: true,
    placeholder: '请选择与会人员',
    colSpan: 24,
  },
  {
    label: '会议描述',
    prop: 'description',
    component: 'textarea',
    required: true,
    placeholder: '请输入会议描述',
    colSpan: 24,
  },
])

// 控制表单弹窗显示
const showFormDialog = ref(false)

// 获取数据
const fetchData = async () => {
  listLoading.value = true
  try {
    list.value = mockData
    total.value = mockData.length
  } catch (error) {
    console.error('获取数据失败:', error)
    list.value = mockData
    total.value = mockData.length
  } finally {
    listLoading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  queryForm.limit = size
  queryForm.page = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  queryForm.page = page
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryForm.meetingTitle = ''
  queryForm.location = ''
  queryForm.page = 1
  fetchData()
}

// 查询数据
const queryData = () => {
  queryForm.page = 1
  fetchData()
}

// 设置选中的行
const setSelectRows = (selection: any[]) => {
  selectRows.value = selection
}

// 查看详情
const handleDetails = (row: any) => {
  router.push({
    name: 'ContractsDetails',
    query: {
      id: row.id,
      title: row.meetingTitle,
    },
  })
}

// 表单提交处理
const handleFormSubmit = (formData: any) => {
  formLoading.value = true
  setTimeout(() => {
    console.log('表单提交的数据:', formData)
    isEditMode.value = false
    showFormDialog.value = false
    formLoading.value = false
    form.value = {}
    fetchData()
    ElMessage.success(isEditMode.value ? '编辑成功!' : '新增成功!')
  }, 500)
}

// 组件激活时刷新数据
onActivated(() => {
  fetchData()
})

// 组件挂载前初始化数据
onBeforeMount(() => {
  fetchData()
})
</script>

<style scoped>
.qs-query-form {
  display: inline-block;
}

/* 保持原有样式 */
.qs-table-container {
  margin-top: 16px;
}

.qs-y-table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
}

.header-label {
  display: flex;
  align-items: center;
}

.header-label-title {
  font-size: 16px;
  font-weight: 600;
}

.header-query {
  display: flex;
  align-items: center;
  gap: 16px;
}
</style>
